package repository

import (
	model "antiquity_map/internal/models"
	"strconv"

	"gorm.io/gorm"
)

type DataRepository interface {
	GetAllRecords(locationID string, page, pageSize string) ([]model.SingleRecord, int64, error)
	GetRecordID(locationID, userID, collectionID, currentTime string) error
}

type dataRepository struct {
	db *gorm.DB
}

func NewDataRepository(db *gorm.DB) DataRepository {
	return &dataRepository{db: db}
}

func (r *dataRepository) GetAllRecords(locationID string, page, pageSize string) ([]model.SingleRecord, int64, error) {
	var records []model.SingleRecord
	var total int64

	pageNum, _ := strconv.Atoi(page)
	if pageNum <= 0 {
		pageNum = 1
	}

	limit, _ := strconv.Atoi(pageSize)
	if limit <= 0 {
		limit = 10
	}

	offset := (pageNum - 1) * limit

	// 计算总数
	result := r.db.Model(&model.CollectionRecord{}).
		Where("location_id = ?", locationID).
		Count(&total)
	if result.Error != nil {
		return nil, 0, result.Error
	}

	// 查询指定字段，包括关联表中的数据
	result = r.db.Model(&model.CollectionRecord{}).
		Select("collection_records.collection_id, users.nick_name as collector_nick_name, collection_records.last_update_time, collection_records.thumbnail").
		Joins("LEFT JOIN users ON collection_records.collector_account = users.account").
		Where("collection_records.location_id = ?", locationID).
		Offset(offset).
		Limit(limit).
		Scan(&records)

	if result.Error != nil {
		return nil, 0, result.Error
	}

	return records, total, nil
}

func (r *dataRepository) GetRecordID(locationID, userID, collectionID, currentTime string) error {
	// 	var record model.CollectionRecord
	// 	result := r.db.Model(&model.CollectionRecord{
	// CollectionID: collectionID,
	// LocationID:   locationID,
	// CollectorAccount: userID,
	// FirstCollectionTime: currentTime,
	// 	}).Create(&record)

	return nil
}
